var ns, UIAlbumBrowser, aMapLBS, db;
var app = new Vue({
    el: '#app',
    data: {
        ID: 0,
        form: {
            PatrolName: '',
            PatrolNumber: '',
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            CheckStatus: '1',
            TaskCompleteContent: '',
            GPSLocation: ''
        },
        PlanType: 3,
        imglist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,
        maxuploadcount: CONFIG.maxuploadcount,
        planform: {},
        list: [],
    },
    methods: {
        get_data: function () {
            var that = this;
            that.get_data_frm();//获取任务信息
            that.get_data_file();//获取附件信息
        },
        get_data_frm: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_PlanTask WHERE ID=${that.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                // console.log('SELECT-Sys_PlanTask')
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    if (ret.data.length > 0) {
                        that.form = ret.data[0];
                        that.get_data_plan();
                        that.StartBmap();
                    }
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        get_data_file: function () {
            var that = this;
            let seltaskfilesql = `SELECT * FROM Sys_File WHERE TaskID=${that.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: seltaskfilesql
            }, function (ret, err) {
                // console.log('SELECT-Sys_File')
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    that.imglist = ret.data;
                    that.imgindex = ret.data.length;
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        get_data_plan: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_Plan WHERE ID=${that.form.PlanTaskID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                if (ret.status) {
                    if (ret.data.length > 0) {
                        that.planform = ret.data[0];
                    }
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
            let seltasksql = `SELECT * FROM Sys_PlanTask WHERE PlanTaskID=${that.form.PlanTaskID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: seltasksql
            }, function (ret, err) {
                if (ret.status) {
                    that.list = ret.data;
                }
            });
        },
        do_save: function () {
            var that = this;
            if (that.form.IsAllowUpload == 'true' && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.form.CheckStatus == '2') { //异常
                api.confirm({
                    title: '提示',
                    msg: '当前结果异常,是否需要上报异常记录?',
                    buttons: ['上报异常', '直接完成']
                }, function (ret, err) {
                    var ServiceStatus = -1;
                    if (ret.buttonIndex == 1) {
                        ServiceStatus = 1;
                    } else if (ret.buttonIndex == 2) {
                        ServiceStatus = 0;
                    }
                    if (ServiceStatus > -1) {
                        that.do_save_process(ServiceStatus);
                    }
                });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function () {
            api.sendEvent({
                name: 'reloadtaskoff',
            });
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            var nowDate = moment().format('YYYY-MM-DD HH:mm');
            //插入附件
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    let filesql = `INSERT INTO Sys_File (ID,TaskID,FilePath,PlanTaskID) VALUES (0,${that.ID},'${that.imglist[i].url}',${that.form.PlanTaskID});`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: filesql,
                    }, function (ret, err) {
                    });

                }
            }

            //获取当前任务Index
            let result = that.list.findIndex((val) => {
                return val.ID == that.ID;
            });
            //更新下一条任务
            if (result > -1 && (that.list.length - 1) != result) {
                let nextform = that.list[result + 1];
                let strnextsql = `UPDATE Sys_PlanTask SET CanPunchCard='true'  WHERE ID=${nextform.ID}`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strnextsql
                }, function (ret, err) {
                });
            }

            //更新计划任务：当任务更新到第一条或最后一条时，更改状态
            if (result == 0) {
                let strnextsql = `UPDATE Sys_Plan SET CheckStartTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strnextsql
                }, function (ret, err) {
                });
            }
            if (result > -1 && (that.list.length - 1) == result) {
                let strnextsql = `UPDATE Sys_Plan SET TaskStatus=3,TaskStatusDesc='已完成',CheckEndTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strnextsql
                }, function (ret, err) {
                });
            }

            //更新任务
            let newCheckStatus = that.form.CheckStatus == '1' ? 1 : 2;
            let newIsInvalidComplete = that.form.CheckStatus == '1' ? false : true;
            let newIsAllowCard = that.form.IsAllowCard == 'true' ? true : false;
            let username = api.getPrefs({ sync: true, key: 'username' });
            let headimg = api.getPrefs({ sync: true, key: 'headimg' });

            let strsql = `UPDATE Sys_PlanTask SET TaskStatus=3,APPUpload=1,IsMiss='false',CheckStatus=${newCheckStatus},IsInvalidComplete='${newIsInvalidComplete}',IsSupplementCard='${newIsAllowCard}',TaskCompleteContent='${that.form.TaskCompleteContent}',TaskCompleteTime='${nowDate}',GPSLocation='${that.form.GPSLocation}',TaskChargeManName='${username}',TaskChargeManHeaderImg='${headimg}' WHERE ID=${that.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
                if (ret.status) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    if (ServiceStatus == 1) {
                        that.do_save_quality();
                    }
                    setTimeout(function () {
                        api.closeWin();
                    }, 1000)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });

        },
        //调用接口生成整改工单
        do_save_quality: function () {
            var that = this;
            let strsql = `UPDATE Sys_PlanTask SET IsAbnormal='true' WHERE ID=${that.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
                if (ret.status) {
                    api.toast({
                        msg: '异常巡查记录已上报',
                        duration: 2000,
                        location: 'bottom'
                    });
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 3000,
                        location: 'bottom'
                    });
                }
            });
        },
        select_all_active: function (CheckStatus) {
            var that = this;
            if (that.form.TaskStatus == '3'&&that.form.IsAllowCard=='false') {
                return;
            }
            that.form.CheckStatus = CheckStatus;
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        UIAlbumBrowser_transPath: function () {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function (ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        remove_img: function (index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                }
            }
        },
        StartBmap: function () {
            var that = this;
            if (that.form.TaskStatus == '3'&&that.form.IsAllowCard=='false') {
                return;
            }
            ns.confirmPer('location', function () {
                aMapLBS.configManager({
                    accuracy: 'tenMeters',
                    filter: 1
                }, function(ret, err) {
                    // console.log(JSON.stringify(ret));
                    if (ret.status) {
                        // 禁止屏幕休眠
                        // api.setKeepScreenOn({
                        //     keepOn: true
                        // });
                        that.StartLocation();
                    };
                });
            })
        },
        StartLocation: function () {
            var that = this;
            if (that.form.TaskStatus == '3'&&that.form.IsAllowCard=='false') {
                return;
            }
            aMapLBS.singleAddress({
                timeout: 2
            }, function (ret) {
                if (ret.status) {
                    that.form.GPSLocation = ret.address.province + ret.address.city +
                        ret.address.district + ret.address.street + ret.address.number;
                }
            });
        },
        do_viewimages: function (activeIndex, IsLine) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (IsLine == 1) {
                    imageUrls.push(that.imglist[i].FilePath);
                }
                else {
                    imageUrls.push(that.imglist[i].url);
                }

            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        // 异常上报记录已分配-跳转到对应的工单
        onOpenOrder: function () {
            // var that = this;
            // //GongdanType  异常上报类型 1-维修工单 2-整改工单
            // //判断是报修工单还是整改工单
            // if(that.form.GongdanID&&that.form.GongdanType==1){
            //     ns.openWin('home_task_con_frm', '报修工单详情', {
            //         id: that.form.GongdanID,
            //     });
            // }
            // if(that.form.GongdanID&&that.form.GongdanType==2){
            //     ns.openWin('qualitycontroldetail_frm', '整改工单详情', {
            //         id:that.form.GongdanID,
            //     })
            // }
        },
    }
});
apiready = function () {
    api.parseTapmode();
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    // 引入aMapLBS定位
    aMapLBS = api.require('aMapLBS');
    ns = window.Foresight.Util;
    db = api.require('db');
    app.ID = api.pageParam.id || 0;
    toast = new auiToast();

    aMapLBS.updateLocationPrivacy({
        privacyAgree: 'didAgree',
        privacyShow: 'didShow',
        containStatus: 'didContain'
    });
    
    db.openDatabase({
        name: 'prodemotest'
    }, function (ret, err) {
        if (!ret.status) {
            api.toast({
                msg: err,
                duration: 2000,
                location: 'bottom'
            });
        }
        else {
            app.get_data();
        }
    });

    api.addEventListener({
        name:'viewdisappear'
    }, function(ret, err){        
        aMapLBS.stopUpdatingLocation();//取消定位
    });
}
